package com.lwz.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.*;
import com.lwz.servicebase.exceptionhandler.MyException;
import com.lwz.util.R;
import com.lwz.vod.service.VodService;
import com.lwz.vod.util.ConstantVodUtils;
import com.lwz.vod.util.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author Lw中
 * @date 2020/11/14 17:36
 */

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    /**
     * LWZ TODO : 2020/11/16 视频相关操作
     */

    @Autowired
    private VodService vodService;

    /**
     * 上传视频，返回视频的id
     * @param file
     * @return
     */
    @PostMapping("/uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file) {
        String videoId = vodService.uploadVideoAly(file);
        return R.ok().data("videoId", videoId);
    }

    @DeleteMapping("/removeAlyVideo/{id}")
    public R removeAlyVideo(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            return R.ok();
        }catch(Exception e) {
            e.printStackTrace();
            throw new MyException(20001,"删除视频失败");
        }
    }

    @DeleteMapping("/delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return R.ok();
    }

    /**
     * 根据视频的id获取视频的播放凭证
     * @param id
     * @return
     */
    @GetMapping("/getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            DefaultAcsClient initVodClient = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            // 创建获取凭证request和response
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 像request设置视频id
            request.setVideoId(id);
            // 调用方法获取凭证
            GetVideoPlayAuthResponse acsResponse = initVodClient.getAcsResponse(request);
            String playAuth = acsResponse.getPlayAuth();
            return R.ok().data("playAuth", playAuth);
        } catch (Exception e) {
            throw new MyException(20001, "获取凭证失败");
        }
    }

}
